package com.qcby.byc.demo0422.config;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.qcby.byc.demo0422.interceptor.LoginInterceptor;
import com.qcby.byc.demo0422.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.format.DateTimeFormatter;

/**
 * @className: WebMvcConfig
 * @description:
 * @author: lxt
 * @create: 2021-04-26 20:31
 **/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 文件上传路径前缀
     */
    @Value("${file.path.prefix}")
    public String filePrefix;
    /**
     * 本地磁盘目录
     */
    @Value("${file.path.upload}")
    public String uploadLocalPath;

//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(loginInterceptor()).addPathPatterns("/**")
//                // 那些路径不拦截
//                .excludePathPatterns("/login/**","/file/**","/error","/demo0528/**");
//    }

    /**
     * @Title: addResourceHandlers
     * @Description:  映射本地磁盘为静态目录
     * @param: registry
     * @throws:
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        FileUtil.filePrefix = filePrefix;
        FileUtil.uploadLocalPath = uploadLocalPath;
        registry.addResourceHandler(filePrefix +"/**").addResourceLocations("file:"+uploadLocalPath);
    }

    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }




    private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String dateFormat = "yyyy-MM-dd";
    /**
     *@Bean注解  注入到spring中，有spring管理
     *
     * @Bean  <bean id="xxx"></bean>
     * @return
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.simpleDateFormat(dateTimeFormat);
            builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
            builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
        };
    }
}
